package user

import (
	"errors"
	"time"

	"gitcode.com/G-YT/baoyou/server/global"
	"gitcode.com/G-YT/baoyou/server/model/manager"
	"gitcode.com/G-YT/baoyou/server/model/user"
	userReq "gitcode.com/G-YT/baoyou/server/model/user/request"
	"gitcode.com/G-YT/baoyou/server/utils"
	"github.com/google/uuid"
	"gorm.io/gorm"
)

type UserService struct{}

const (
	MINI_APP_LATEST_ID     = "wxae78daad54f99c72"
	MINI_APP_LATEST_SECRET = "e0558655a487724bfcf14640944b6df0"
	//tokenURL               = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s"
	//getWXACodeUnlimitURL   = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=%s"
)

type TokenResponse struct {
	AccessToken string `json:"access_token"`
	ExpiresIn   int    `json:"expires_in"`
}

type QRCodeRequest struct {
	Scene     string `json:"scene"`
	Page      string `json:"page"`
	Width     int    `json:"width"`
	AutoColor bool   `json:"auto_color"`
	LineColor struct {
		R int `json:"r"`
		G int `json:"g"`
		B int `json:"b"`
	} `json:"line_color"`
}

//var dictionaryService = new(system.DictionaryService)

// Register 注册
// Author: [g-qs](https://github.com/g-qs)
func (userService *UserService) Register(u *user.User) (ID uint, err error) {
	err = global.GVA_DB.Transaction(func(tx *gorm.DB) error {
		// 否则 附加uuid 密码hash加密 注册
		u.Password = utils.BcryptHash(u.Password)
		u.UUID = uuid.New()
		// 获取健管师信息
		var hm manager.HealthManager
		if hmErr := tx.Where("hm_id", u.HealthManagerID).First(&hm).Error; hmErr != nil {
			return hmErr
		}
		// 加健管师推广人数
		*hm.PromoteNum += 1
		if uhm := tx.Model(&manager.HealthManager{}).Where("hm_id", u.HealthManagerID).Update("promote_num", *hm.PromoteNum).Error; uhm != nil {
			return uhm
		}
		// 创建User数据
		uErr := tx.Create(&u).Error
		if err != nil {
			return uErr
		}
		return nil
	})
	ID = u.ID
	return

}

// Login 登陆
// Author: [g-qs](https://github.com/g-qs)
func (userService *UserService) Login(u *user.User) (userInter *user.User, err error) {
	var userInfo user.User
	err = global.GVA_DB.Where("phone = ?", u.Phone).First(&userInfo).Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		return nil, errors.New("手机号不存在")
	}
	if err == nil {
		if ok := utils.BcryptCheck(u.Password, userInfo.Password); !ok {
			return nil, errors.New("密码错误")
		}
	}
	return &userInfo, err
}

// FindUserByWhere 通过条件获取单条用户信息
// Author: [g-qs](https://github.com/g-qs)
func (userService *UserService) FindUserByWhere(condition map[string]interface{}, fields string) (userInfo *user.User, err error) {
	err = global.GVA_DB.Select(fields).Where(condition).Limit(1).First(&userInfo).Error
	return
}

// UpdateDataById 根据ID修改一条数据
// Author: [g-qs](https://github.com/g-qs)
func (userService *UserService) UpdateDataById(ID uint, info map[string]interface{}) (err error) {
	err = global.GVA_DB.Debug().Model(&user.User{}).Where("id = ?", ID).Updates(info).Error
	return
}

// FindUserByID 通过条件获取单条用户信息
// Author: [g-qs](https://github.com/g-qs)
func (userService *UserService) FindUserByID(id uint) (userInfo user.User, err error) {
	err = global.GVA_DB.Preload("UrgentCard").Preload("Division").Preload("HealthManager", func(db *gorm.DB) *gorm.DB {
		return db.Preload("HealthManageCenter", func(db *gorm.DB) *gorm.DB {
			return db.Preload("CreatorInfo")
		})
	}).First(&userInfo, id).Error
	return
}

// GetUserData 根据ID获取用户信息
// Author: [g-qs](https://github.com/g-qs)
func (userService *UserService) GetUserData(ID uint) (result user.User, err error) {
	err = global.GVA_DB.Model(&user.User{}).Where("id = ?", ID).Find(&result).Error
	return
}

// UpdateUser 根据用户ID修改信息
func (userService *UserService) UpdateUser(id uint, req userReq.UpdateUserRequest) error {
	updates := map[string]interface{}{
		"name":          req.Name,
		"avatar":        req.Avatar,
		"sex":           req.Sex,
		"phone":         req.Phone,
		"birthday":      req.Birthday,
		"province":      req.Province,
		"city":          req.City,
		"area":          req.Area,
		"addr":          req.Addr,
		"contact":       req.Contact,
		"contact_phone": req.ContactPhone,
	}
	return global.GVA_DB.Model(&user.User{}).Where("id = ?", id).Updates(updates).Error
}

func (userService *UserService) AddPoints(id uint, points int, days int) error {
	// 简化实现：直接累加积分
	return global.GVA_DB.Model(&user.User{}).Where("id = ?", id).Update("points", gorm.Expr("points + ?", points)).Error
}

func (userService *UserService) GetUserByVipLevel(vipType string) error {
	// 预留实现，当前返回 nil 保证编译通过
	return nil
}

func (userService *UserService) GetUserDivisionInfo(id uint) (any, error) {
	// 预留实现，当前返回空
	return map[string]any{}, nil
}

func (userService *UserService) GetUserDivisionRank() (any, error) {
	// 预留实现，当前返回空列表
	return []any{}, nil
}

func (userService *UserService) GetCountWeeklyPoints(userID uint) (any, error) {
	// 预留实现，返回空数据
	return map[string]any{}, nil
}

func (userService *UserService) TranslateTable() error {
	// 预留实现
	return nil
}

func (userService *UserService) UpsertLoginUser(phone string, serviceStationID uint, healthManagerID uint, loginType string) (result user.User, err error) {
	err = global.GVA_DB.Transaction(func(tx *gorm.DB) error {
		var userInfo user.User
		// 判读账号是否存在
		userInfoErr := tx.Where("phone = ?", phone).First(&userInfo).Error
		if userInfoErr != nil {
			// 不存在创建数据
			if errors.Is(userInfoErr, gorm.ErrRecordNotFound) {
				nu := user.User{
					Phone:            phone,
					ServiceStationID: serviceStationID,
					HealthManagerID:  healthManagerID,
					UUID:             uuid.New(),
					Name:             phone,
					LastLoginAt:      time.Now(),
					LastLoginType:    loginType,
				}
				if cErr := tx.Create(&nu).Error; cErr != nil {
					return errors.New("创建用户失败")
				}
				// 如果接收到健管师ID
				if healthManagerID != 0 {
					var hm manager.HealthManager
					if hErr := tx.Where("hm_id", healthManagerID).First(&hm).Error; hErr != nil {
						return errors.New("查询健管师失败")
					}
					// 加健管师推广人数
					*hm.PromoteNum += 1
					if uhm := tx.Model(&manager.HealthManager{}).Where("hm_id", healthManagerID).Update("promote_num", *hm.PromoteNum).Error; uhm != nil {
						return errors.New("更新健管师推广人数失败")
					}
				}
				result = nu
				return nil
			}
		}
		updates := map[string]interface{}{
			"last_login_at":   time.Now(),
			"last_login_type": loginType,
		}
		if uErr := tx.Model(&user.User{}).Where("id = ?", userInfo.ID).Updates(updates).Error; uErr != nil {
			return errors.New("更新用户登录信息失败")
		}
		result = userInfo
		return nil
	})
	return
}
